package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.data.entity.Good;
import team.bluepen.supermarket.util.StringUtil;
import team.bluepen.supermarket.web.base.DataServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 商品编辑
 * @author Kai
 */
@WebServlet(name = "GoodEditServlet", urlPatterns = "/api/good-edit")
public class GoodEditServlet extends DataServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        if (!checkUserRole(req)) {
            resp.sendRedirect(requestSource);
            return;
        }
        String name = req.getParameter(Constant.GOOD_NAME_PARAM);
        String row = req.getParameter(Constant.GOOD_ROW_PARAM);
        String state = req.getParameter(Constant.GOOD_STATE_PARAM);

        if (row == null) {
            resp.sendRedirect(requestSource + "?error=" + Error.ERROR_NULL.getValue());
            return;
        }

        Good oldGood = goodRepository.query(row);
        int amount = 0, price = 0;
        String amountParameter = req.getParameter(Constant.GOOD_AMOUNT_PARAM);
        if (StringUtil.isEmpty(amountParameter)) {
            amount = oldGood.getAmount();
        } else {
            amount = Integer.parseInt(amountParameter);
        }

        String priceParameter = req.getParameter(Constant.GOOD_PRICE_PARAM);
        if (StringUtil.isEmpty(priceParameter)) {
            price = oldGood.getPrice();
        } else {
            price = Integer.parseInt(priceParameter);
        }


        Good editGood = new Good()
                .setId(oldGood.getId())
                .setAmount(Math.max(amount, 0))
                .setPrice(Math.max(price, 0))
                .setState(state)
                .setName(StringUtil.isEmpty(name) ? oldGood.getName() : name)
                .setRow(row);

        Error error = goodRepository.insert(editGood);
        resp.sendRedirect(requestSource + "?error=" + error.getValue());
    }
}
